<?php

namespace app\admin\controller\yungift;

use addons\yungift\model\Group;
use addons\yungift\model\Member;
use app\common\controller\Backend;
use addons\yungift\model\MemberLog as MemberLogModel;

/**
 * 成员日志
 */
class MemberLog extends Backend
{
    /**
     * @var MemberLogModel
     */
    protected $model;

    // 联表查询，解决字段冲突
    protected $relationSearch = true;

    // 初始化
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new MemberLogModel();

        $this->view->assign('actionList', $this->model::getActionList());
        $this->assignconfig('actionList', $this->model::getActionList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $memberId = $this->request->request('member_id');
        $member = $memberId ? Member::get($memberId) : null;
        if ($this->request->isAjax()) {
            // 重载查询条件
            $filter = json_decode($this->request->get('filter'), true);
            $op = json_decode($this->request->get('op'), true);
            if (array_key_exists('member.group_id', $filter)) {
                if ($filter['member.group_id']) {
                    $filter['member.group_id'] = Group::getRelationIds($filter['member.group_id']);
                    $op['member.group_id'] = 'in';
                } else {
                    $filter['member.group_id'] = 0;
                    $op['member.group_id'] = '=';
                }
            }
            $this->request->get(['filter' => json_encode($filter), 'op' => json_encode($op)]);

            // 通用查询条件
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $query = $this->model->with(['member_data' => ['group_data']])
                ->field('member_log.*')
                ->join([Member::getTableName() => 'member'], 'member.id=member_log.member_id', 'LEFT')
                ->where($where)
                ->where('member.id is not null')
                ->where('member.deleted_at is null');
            if ($memberId) {
                $query->where(['member_log.member_id' => $memberId]);
            }
            $list = $query->order($sort, $order)->limit($offset, $limit)->paginate($limit);

            $result = array(
                'total' => $list->total(),
                'rows'  => $list->items(),
            );

            return json($result);
        }
        $this->view->assign('member', $member);
        $this->view->assign('memberId', $memberId);
        $this->assignconfig('memberId', $memberId);

        // 分组列表
        $groupList = Group::getTreeList();
        $groupMap = ['0' => '未分组'];
        foreach ($groupList as $item) {
            $groupMap[$item['id']] = $item['name'];
        }
        $this->view->assign('groupMap', $groupMap);
        $this->assignconfig('groupMap', $groupMap);


        return $this->view->fetch();
    }
}
